<?php

namespace App\Api\Service;

use App\Api\Repositories\Search\SearchRepositories;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Laravel\Socialite\Facades\Socialite;

class SearchService extends BaseService
{
    protected $repositories;

    public function __construct()
    {
        $this->repositories = new SearchRepositories();
    }

    /**
     * 根据搜索条件获取内部和外部符合条件的数据
     *
     * @param int $uid
     * @param array $search
     * @return void
     */
    public function get_search_result($uid, $search)
    {
        // 扣款，添加至数据库
        DB::beginTransaction();
        try {
            $sys_setting_repositories = new \App\Api\Repositories\Sys\SysSettingRepositories();
            $need_money = $sys_setting_repositories->get(27);
            $user_funds_repositories = new \App\Api\Repositories\User\UserFundsRepositories();
            $res_two = $this->repositories->create_data($uid, $search);
            $res_one = $user_funds_repositories->update_data($uid, 'money', '-' . $need_money, '搜索', '搜索id为' . $res_two->id);
            $search_id = $res_two->id;
            if ($res_one && $res_two) {
                DB::commit();
            } else {
                throwBusinessException('搜索失败');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            throwBusinessException($e->getMessage());
        }
        // 整理数据
        $make_search = $this->make_search_use_select($search);
        // 搜索内部数据
        $user_detail_repositories = new \App\Api\Repositories\User\UserDetailRepositories();
        $interior_result = $user_detail_repositories->select_interior_data($make_search);
        // 搜索外部数据(在这里整理数据)
        $exterior_result = $this->repositories->select_exterior_data($uid, $make_search);
//        $exterior_results = $this->repositories->select_exterior_data($uid, $make_search);
        // 整理结果数据并返回
        $ids = [];
        $make_search = $this->make_search_use_show($search);
        $search_repositories = new \App\Api\Repositories\Search\SearchResultRepositories();
        foreach ($interior_result as $key => $v) {
            $interior_result[$key] = $this->make_interior_result_use_list_show($uid, $v);
            $ids[] = $interior_result[$key]['id'];
            $search_repositories->create_data($search_id, substr($interior_result[$key]['id'], 1, 100), 'i');
        }
        foreach ($exterior_result as $key => $v) {
            $exterior_result[$key] = $this->make_exterior_result_use_list_show($uid, $v);
            $ids[] = $exterior_result[$key]['id'];
            $search_repositories->create_data($search_id, substr($exterior_result[$key]['id'], 1, 100), 'e');
        }
        $this->repositories->save_result_ids($uid, $ids);
        return [
            'search' => $make_search,
            'number' => count($ids),
            'interior_data' => $interior_result,
            'exterior_data' => $exterior_result
        ];
    }

    /**
     * 根据编号获取搜索内容详情
     *
     * @param int $uid
     * @param int $number
     * @return void
     */
    public function get_search_detail($uid, $number, $type = 0)
    {
        if ($type == 1) {
            $id = $number;
        } else {
            // 通过编号获取搜索id
            $id = $this->repositories->use_number_get_id($uid, $number);
        }

        // 获取详细内容,并设置为已读
        $data = $this->use_id_select_data($id);
        if ($uid != 0) {
            $log_user_browse = new \App\Api\Repositories\Log\LogUserBrowseRepositories();
            $log_user_browse->set_is_read($id, $uid);
            // 获取是否已收藏
            $log_user_collect = new \App\Api\Repositories\Log\LogUserCollectRepositories();
            $data['is_collect'] = $log_user_collect->get_is_collect($id, $uid);
        } else {
            $data['is_collect'] = false;
        }

        // 内部信息/外部信息 的联系方式处理， 图片处理
        $log_pay_show_contact = new \App\Api\Repositories\Log\LogPayShowContactRepositories();
        if (substr($id, 0, 1) == 'i') {
            $data['type'] = "内源数据";
            foreach (['email', 'qq', 'weixin'] as $field) {
                $data["is_show_" . $field] = false;
                if ($data[$field] != '') {
                    $data[$field] = '******';
//                    $data["is_show_" . $field] = boolval($log_pay_show_contact->get_data_status($uid, $id, $field));
//                    if ($data["is_show_" . $field] == false) {
//                        $data[$field] = '******';
//                    }
                }
            }
            $data['photo_number'] = 0;
            foreach (['general_photo', 'life_photo', 'work_photo', 'study_photo', 'travel_photo', 'other_photo'] as $value) {
                $data[$value] != '' ? $data['photo_number']++ : '';
            }
        } else {
            $data['type'] = "外源数据";
            foreach (['email', 'qq', 'weixin', 'phone'] as $field) {
                $data['contact_info']["is_show_" . $field] = false;
                if (isset($data['contact_info'][$field]) && $data['contact_info'][$field] != '') {
                    $data['contact_info'][$field] = '******';
//                    $data['contact_info']["is_show_" . $field] = boolval($log_pay_show_contact->get_data_status($uid, $id, $field));
//                    if ($data['contact_info']["is_show_" . $field] == false) {
//                        $data['contact_info'][$field] = '******';
//                    }
                }
            }
            if (isset($data['img_list'])) {
                $data['photo_number'] = count($data['img_list']);
            } else {
                $data['photo_number'] = 0;
            }

        }

        $data['search_id'] = $id;
        return $data;
    }

    /**
     * 收藏
     *
     * @param [type] $uid
     * @param [type] $search_id
     * @return void
     */
    public function collect_search_data($uid, $search_id)
    {
        $log_user_collect = new \App\Api\Repositories\Log\LogUserCollectRepositories();
        $is_collect = $log_user_collect->set_is_collect($search_id, $uid);
        return [$is_collect, $is_collect ? '收藏成功' : '取消成功'];
    }

    /**
     * 获取联系方式
     *
     * @param int $uid
     * @param string $search_id
     * @param string $type
     * @return void
     */
    public function get_contact($uid, $search_id, $type)
    {
        $dict = ['qq' => 'QQ', 'email' => '邮箱', 'weixin' => '微信', 'phone' => '手机号'];
        // 支付
        // DB::beginTransaction();
        // try{
        //     $sys_setting_repositories = new \App\Api\Repositories\Sys\SysSettingRepositories();
        //     $need_money = $sys_setting_repositories->get(25);
        //     $user_funds_repositories = new \App\Api\Repositories\User\UserFundsRepositories();
        //     $content = (substr($search_id, 0, 1) == 'i' ? '查看会员id为' : '查看外源数据id为') . substr($search_id, 1, 100) . '的' . $dict[$type];
        //     $res = $user_funds_repositories->update_data($uid, 'money', '-' . $need_money, '查看联系方式', $content, $search_id . $type);
        //     if($res){
        //         DB::commit();
        //     }else{
        //         throwBusinessException('支付失败');
        //     }
        // }catch(\Exception $e){
        //     DB::rollBack();
        //     throwBusinessException($e->getMessage());
        // }
        // 判断是否支付
        // $LogPayShowContactRepositories = new \App\Api\Repositories\Log\LogPayShowContactRepositories();
        // if($LogPayShowContactRepositories->get_data_status($uid, $search_id, $type) != 1){
        //     throwBusinessException('请先支付费用');
        // }
        // 返回数据
        $data = $this->use_id_select_data($search_id);
        if (substr($search_id, 0, 1) == 'i') {
            return $data[$type];
        } else {
            return $data['contact_info'][$type];
        }
    }

    /**
     * 将搜索条件数据修改便于内部、外部搜索的格式
     * 年龄设置区间，身高设置区间，关键词改为数组，内部数据使用in查询，年龄和身高列举出全部情况
     *
     * @param array $search
     * @return void
     */
    private function make_search_use_select($search)
    {
        // 通过年龄区间条件，获取内部使用的 birthday 参数，与外部使用的 age_section 参数
        $search['age_section'] = [$search['min_age'], $search['max_age']];
        if ($search['min_age'] == 1 && $search['max_age'] == 150) {
            $search['birthday'] = ['*'];
        } else {
            $search['birthday'] = [];
            for ($i = $search['age_section'][0]; $i <= $search['age_section'][1]; $i++) {
                $year = date("Y", time()) - $i;
                for ($month = 1; $month <= 12; $month++) {
                    // $search['birthday'][] = date("Y-m", strtotime($year . '-' . $month));
                    $search['birthday'][] = $year . '-' . $month;
                }
            }
        }
        // 通过身高区间条件，获取内部使用的 height 参数，与外部使用的 height_section 参数
        if ($search['height'] != '') {
            $search['height_section'] = explode('-', $search['height']);
            $search['height'] = [];
            for ($height = $search['height_section'][0]; $height <= $search['height_section'][1]; $height++) {
                $search['height'][] = $height;
            }
        }
        $search['keyword'] = explode(',', $search['keyword']);
        return $search;
    }

    /**
     * 将搜索条件整理为接口展示需要的格式
     *
     * @param array $search
     * @return void
     */
    private function make_search_use_show($search)
    {
        $res = [];
        foreach ($search as $key => $value) {
            if ($key == 'keyword') {
                $keywords = explode(',', $value);
                if ($keywords[0] != '') {
                    $res = array_merge($res, $keywords);
                }
                continue;
            } elseif ($key == 'height') {
                $value = $value != '100-250' ? implode('cm~', explode('-', $value)) . 'cm' : '';
            } elseif ($key == 'min_age') {
                if ($search['min_age'] == 1 && $search['max_age'] == 150) {
                    $value = '';
                } else {
                    $value = implode('~', [$value, $search['max_age']]);
                }
            } elseif ($key == 'max_age') {
                $value = '';
            }
            if ($value != '') {
                $res[] = $value;
            }
        }
        return $res;
    }

    /**
     * 根据搜索id获取相关内容
     * 内部信息是查询数据库，转成数组格式，
     * 外部信息是调用接口返回值，本就是数组
     *
     * @param int $search_id
     * @return array
     */
    private function use_id_select_data($search_id)
    {
        if (substr($search_id, 0, 1) == 'i') {
            // 内部信息
            $user_detail_repositories = new \App\Api\Repositories\User\UserDetailRepositories();
            $data = $user_detail_repositories->use_id_get_data(substr($search_id, 1, 100))->toArray();
        } else {
            // 外部信息
            $sedr = new \App\Api\Repositories\Search\SearchExogenousDataRepositories();
            $data = $sedr->use_id_get_data(substr($search_id, 1, 100));
        }
        if (!$data) {
            throwBusinessException('无此搜索结果');
        }
        return $data;
    }
}
